const app = getApp()
import { saveFile } from '../../api/index.js'
const uploadOss = require('../../utils/upload/uploadImg.js')
import { uuid } from '../../utils/util'

Page({
  data: {
    form: {
      passedQualityCertification: '',
      passedHealthCertification: '',
      passedEnvironmentCertification: '',
      certificationFileIds: [],
      healthCertificationFileIds: [],
      environmentCertificationFileIds: [],
    },
    certificationList: [],
    certificationFileIds: [],
    healthCertificationFileIds: [],
    environmentCertificationFileIds: []
  },
  changeRadio ({ detail, target: { dataset: { key } } }) {
    this.setData({
      [`form.${key}`]: JSON.parse(detail)
    })
  },
  delTempFile ({ detail: { currentTarget: { dataset: { key, item, index } } } }) {
    this.data[`${key}`].splice(index, 1)
    this.setData({
      [`${key}`]: this.data[`${key}`]
    })
  },
  delFile ({ detail: { currentTarget: { dataset: { key, item, index } } } }) {
    this.data.form[`${key}`].splice(index, 1)
    this.setData({
      [`form.${key}`]: this.data.form[`${key}`]
    })
  },
  async againFile ({ detail: { currentTarget: { dataset: { key, item, index } } } }) {
    try {
      let _this = this
      let tempFiles = this.data[`${key}`]
      tempFiles[index].success = ''
        _this.setData({
          [`${key}`]: tempFiles
        })
      const fileUrl = await _this.uploadFile(item, 'tempFilePath', tempFiles, index, _this, key)
      if (fileUrl) {
        const { ResultSet } = await saveFile({
          fileList: [{
            fileSize: item.size,
            fileUrl: fileUrl
          }]
        })
        tempFiles.splice(index, 1)
        _this.data.form[key].push({
          uuid: item.uuid,
          fileId: ResultSet.userData.fileIdList[0].fileId,
          fileUrl: ResultSet.userData.fileIdList[0].fileUrl
        })
        _this.setData({
          [`${key}`]: tempFiles,
          [`form.${key}`]: _this.data.form[key]
        })
      } else {
        tempFiles[index].success = 1
        _this.setData({
          [`${key}`]: tempFiles
        })
      }
    } catch (err) {
      console.log(err)
    }
  },
  addFile ({ target: { dataset: { key } } }) {
    let _this = this
    wx.chooseMedia({
      count: 9,
      mediaType: ['image'],
      async success (res) {
        res.tempFiles.forEach(item => {
          item.uuid = uuid()
          item.progress = 0
        })
        _this.data[`${key}`].push(...res.tempFiles)
        _this.setData({
          [`${key}`]: _this.data[`${key}`]
        })
        let tempFiles = _this.data[`${key}`]
        let temFileList = []
        if (tempFiles.length) {
          temFileList = await Promise.all(tempFiles.map(async (item, index) => {
            const fileUrl = await _this.uploadFile(item, 'tempFilePath', tempFiles, index, _this, key)
            if (fileUrl) {
              const { ResultSet } = await saveFile({
                fileList: [{
                  fileSize: item.size,
                  fileUrl: fileUrl
                }]
              })
              return {
                uuid: item.uuid,
                fileId: ResultSet.userData.fileIdList[0].fileId,
                fileUrl: ResultSet.userData.fileIdList[0].fileUrl
              }
            } else {
              tempFiles[index].success = 1
              _this.setData({
                [`${key}`]: tempFiles
              })
            }
          }))
        }
        let tempFileList = temFileList.filter(item => item)
        _this.data.form[key].push(...tempFileList)
        _this.data.form[key].forEach((item) => {
          let rowIndex = tempFiles.findIndex(row => row.uuid === item.uuid)
          if (rowIndex > -1) tempFiles.splice(rowIndex, 1)
        })
        _this.setData({
          [`${key}`]: tempFiles,
          [`form.${key}`]: _this.data.form[key]
        })
      }
    })
  },
  uploadFile (item, key, files, index, that, dataKey) {
    return new Promise((resolve, reject) => {
      uploadOss(item[key],
        (fileUrl) => {
          resolve(fileUrl)
        },
        (err) => {
          resolve()
        },
        files, index, that, dataKey
      )
    })
  },
  preStep () {
    wx.$nav.navigateBack()
  },
  nextStep () {
    if (!this.data.form.passedQualityCertification) {
      wx.showToast({ title: '请仔细检查是否有未填写的数据！', icon: 'none' })
      return 
    } else {
      if (this.data.form.passedQualityCertification === 1 && !this.data.form.certificationFileIds.length) {
        wx.showToast({ title: '请提供质量管理体系相关报告与证书！', icon: 'none' })
        return
      }
    }
    if (!this.data.form.passedHealthCertification) {
      wx.showToast({ title: '请仔细检查是否有未填写的数据！', icon: 'none' })
      return 
    } else {
      if (this.data.form.passedHealthCertification === 1 && !this.data.form.healthCertificationFileIds.length) {
        wx.showToast({ title: '请提供职业健康安全管理体系相关报告与证书！', icon: 'none' })
        return
      }
    }
    if (!this.data.form.passedEnvironmentCertification) {
      wx.showToast({ title: '请仔细检查是否有未填写的数据！', icon: 'none' })
      return 
    } else {
      if (this.data.form.passedEnvironmentCertification === 1 && !this.data.form.environmentCertificationFileIds.length) {
        wx.showToast({ title: '请提供环境管理体系相关报告与证书！', icon: 'none' })
        return
      }
    }
    app.globalData.form = { ...app.globalData.form, ...this.data.form }
    wx.$nav.navigateTo('/pages/certificate/index')
  },
  onLoad () {
    const { form, dropDown } = app.globalData
    if (dropDown.certificationList.length) {
      this.setData({
        certificationList: dropDown.certificationList
      })
    } else {
      app.globalData.getDropDownCallback = res => {
        this.setData({
          certificationList: app.globalData.dropDown.certificationList
        })
      }
    }
    let newForm = { ...this.data.form, ...form }
    this.setData({ form: newForm })
    // this.getSelectList()
    // this.getAddres()
  },
})
